<template>
  <!-- 列表 -->
  <ContentWrap>
    <el-button
      v-if="props.apartmentId"
      type="primary"
      plain
      @click="openForm('create')"
      v-hasPermi="['business:apartment:create']"
    >
      <Icon icon="ep:plus" class="mr-5px" /> 新增
    </el-button>
    <el-button
      v-if="props.apartmentId"
      type="warning"
      plain
      @click="handleImport"
      v-hasPermi="['business:apartment:export']"
    >
      <Icon icon="ep:upload" /> 户型信息导入
    </el-button>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="户型图" align="center" prop="showImage">
        <template #default="{ row }">
          <el-image
            class="h-50px w-50px"
            lazy
            :src="row.showImage"
            :preview-src-list="[row.showImage]"
            preview-teleported
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column label="户型" align="center" prop="houseType">
        <template #default="{row}">
          <p>{{dictList.find(item => item.value == row.houseType)?.label}}</p>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="priceMin">
        <template #default="{row}">
<!--          <p>售价${{row.priceMin}} - {{row.priceMax}}</p>-->
          <p>售价$ {{row.priceMin}} 起</p>
        </template>
      </el-table-column>
      <el-table-column label="房屋面积" align="center" prop="houseArea">
        <template #default="{row}">
          <p>室内：{{row.indoorArea || '-'}} ㎡</p>
          <p>阳台：{{row.balconyArea  || '-'}} ㎡</p>
        </template>
      </el-table-column>
      <el-table-column label="车位" align="center" prop="parkingSpace">
        <template #default="{row}">
          <p>{{row.parkingSpace}}</p>
        </template>
      </el-table-column>
<!--      <el-table-column label="状态" align="center" prop="statusZhCn">
        <template #default="{row}">
          <p>{{row.statusZhCn}}</p>
          <p>({{row.statusEnUs}})</p>
        </template>
      </el-table-column>-->
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['business:apartment:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['business:apartment:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" title="户型导入" width="400">
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="importUrl"
      :auto-upload="false"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      accept=".xlsx, .xls"
      drag
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>仅允许导入 xls、xlsx 格式文件。</span>
          <a href="https://fy2025.hncykj.xyz/admin-api/infra/file/29/get/20251016/apartment_template_house_type_1760586763954.xlsx" download="户型模板.xlsx">
            <el-button size="small" type="text" plain >下载模板</el-button>
          </a>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

    <!-- 表单弹窗：添加/修改 -->
    <ApartmentHouseTypeForm ref="formRef" @success="getList" />
</template>
<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { ApartmentApi } from '@/api/business/apartment'
import ApartmentHouseTypeForm from './ApartmentHouseTypeForm.vue'
import {BizDictTypeApi} from "@/api/business/dicttype";
import {getAccessToken, getTenantId} from "@/utils/auth";

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const props = defineProps<{
  apartmentId?: number // 楼盘/公寓ID（主表的关联字段）
}>()
const loading = ref(false) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  apartmentId: undefined as unknown
})

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.apartmentId,
  (val: number) => {
    if (!val) {
      return
    }
    queryParams.apartmentId = val
    handleQuery()
  },
    { immediate: true, deep: true }
)

const dictList = ref() // 弹窗的是否展示
const getDictDataList = async (id: number) => {
  dictList.value = await BizDictTypeApi.getBizDictDataByTypeId(id)
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ApartmentApi.getApartmentHouseTypePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  if (!props.apartmentId) {
    message.error('请选择一个楼盘/公寓')
    return
  }
  formRef.value.open(type, id, props.apartmentId)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ApartmentApi.deleteApartmentHouseType(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}






const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/business/apartment/apartment-house-type/import-excel'
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表
const handleImport = () => {
  dialogVisible.value = true
  fileList.value = []
}

/** 提交表单 */
const submitForm = async () => {
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId(),
    'apartmentId': props.apartmentId
  }
  formLoading.value = true
  uploadRef.value!.submit()
}

/** 文件上传成功 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
  if (response.code !== 0) {
    message.error(response.msg)
    formLoading.value = false
    return
  }
  message.alert('上传成功')
  formLoading.value = false
  dialogVisible.value = false
  fileList.value = []
  getList()
  // 发送操作成功的事件
  emits('success')
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}
/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}





/** 初始化 **/
onMounted(() => {
  getDictDataList(1)
})
</script>
